package com.mybatis.ext;


import com.mybatis.ext.utils.MybatisHelper;
import com.mybatis.ext.utils.RowSelection;
import com.mybatis.ext.utils.SqlServerPageHelper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.jeecgframework.core.common.dao.jdbc.JdbcDao;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.util.ListUtils;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.vo.datatable.SortDirection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service("WiseCoreService")
@Transactional
public class WiseCoreService {

	@Autowired()
	SqlSessionFactory sqlSessionFactory;

	@Autowired()
    JdbcDao jdbcDao;

	@Autowired
	JdbcTemplate jdbcTemplate;

    public void assembleParam(Map<String,Object> params, HttpServletRequest request){
        for (Object key : request.getParameterMap().keySet()) {
            if ((String[]) request.getParameterMap().get(key) != null) {
                for (int i = 0; i < ((String[]) request.getParameterMap().get(key)).length; i++) {
                    if (((String[]) request.getParameterMap().get(key))[i] != null) {
                        params.put(oConvertUtils.getString(key), ((String[]) request.getParameterMap().get(key))[i]);
                    }
                }
            }
        }
    }


	public void selectDataGrid(String serviceId, Map<String, Object> params, DataGrid dataGrid) {
		String sortName = "";
		SortDirection order = null;
		if(dataGrid.getSort() != null && !dataGrid.getSort().equals("")){
			sortName = dataGrid.getSort();
		}
		int rows = dataGrid.getRows();
		order = dataGrid.getOrder();
		/*
		 * dataGrid.getOrder() 默认返回asc 所以不用判断
		if(dataGrid.getOrder() != null && !dataGrid.getOrder().equals("")){
			order = dataGrid.getOrder();
		}*/
		//从对应路径中，获取SQL [/jeecg/demo/sql/test/JeecgJdbcService_listAllByJdbc.sql]
		//1 根据 serviceId , params 获取mybatyis生成的sql语句
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,params);
		//String countsql = JeecgSqlUtil.getCountSqlBySql(ori_sql);

		SqlServerPageHelper sqlserverPageHelper  = new SqlServerPageHelper(ori_sql, new RowSelection());
		String countsql = sqlserverPageHelper.getCountSql();
		int total = jdbcDao.countByJdbc(countsql);
		dataGrid.setTotal(total);
		if(!sortName.equals("")){
			ori_sql += " ORDER BY ";

			for(String s : sortName.split(",")){
				ori_sql += (s +" "+ order +",");
			}

			ori_sql = ori_sql.substring(0,ori_sql.lastIndexOf(","));

		}
		List<Map<String, Object>> results = jdbcDao.findForJdbcParam(ori_sql, dataGrid.getPage(), dataGrid.getRows());
		dataGrid.setResults(results);
	}

	/**
	 * ibatis 自定以查询
	 * @param serviceId ibatis id
	 * @param params 参数
	 * @param dataGrid
	 * @param isOffset 是否分页
	 */
	public void selectDataGrid(String serviceId, Map<String, Object> params, DataGrid dataGrid, boolean isOffset) {
		String sortName = "";
		SortDirection order = null;
		if(dataGrid.getSort() != null && !dataGrid.getSort().equals("")){
			sortName = dataGrid.getSort();
		}

		order = dataGrid.getOrder();
		/*
		 * dataGrid.getOrder() 默认返回asc 所以不用判断
		if(dataGrid.getOrder() != null && !dataGrid.getOrder().equals("")){
			order = dataGrid.getOrder();
		}*/
		//从对应路径中，获取SQL [/jeecg/demo/sql/test/JeecgJdbcService_listAllByJdbc.sql]
		//1 根据 serviceId , params 获取mybatyis生成的sql语句
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,params);
		//String countsql = JeecgSqlUtil.getCountSqlBySql(ori_sql);
		SqlServerPageHelper sqlserverPageHelper  = new SqlServerPageHelper(ori_sql, new RowSelection());
		String countsql = sqlserverPageHelper.getCountSql();
		int total = jdbcDao.countByJdbc(countsql);
		dataGrid.setTotal(total);
		if(!sortName.equals("")){
			ori_sql += " ORDER BY ";

			for(String s : sortName.split(",")){
				ori_sql += (s +" "+ order +",");
			}

			ori_sql = ori_sql.substring(0,ori_sql.lastIndexOf(","));

		}
		List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
		if(isOffset){
			results = jdbcDao.findForJdbcParam(ori_sql, dataGrid.getPage(), dataGrid.getRows());
		}else{
			results = jdbcDao.findForJdbc(ori_sql);
		}
		dataGrid.setResults(results);
	}

	public void selectDataGrid(String serviceId, Map<String, Object> params, String orders, DataGrid dataGrid) {
		String sortName = "";
		SortDirection order = null;
		if(dataGrid.getSort() != null && !dataGrid.getSort().equals("")){
			sortName = dataGrid.getSort();
		}
		order = dataGrid.getOrder();
		/*
		 * dataGrid.getOrder() 默认返回asc 所以不用判断
		if(dataGrid.getOrder() != null && !dataGrid.getOrder().equals("")){
			order = dataGrid.getOrder();
		}*/
		//从对应路径中，获取SQL [/jeecg/demo/sql/test/JeecgJdbcService_listAllByJdbc.sql]
		//1 根据 serviceId , params 获取mybatyis生成的sql语句
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,params);
		//String countsql = JeecgSqlUtil.getCountSqlBySql(ori_sql);
		SqlServerPageHelper sqlserverPageHelper  = new SqlServerPageHelper(ori_sql, new RowSelection());
		String countsql = sqlserverPageHelper.getCountSql();
		int total = jdbcDao.countByJdbc(countsql);
		dataGrid.setTotal(total);
		if(!sortName.equals("")){
			ori_sql += " ORDER BY ";
			String[] sort = sortName.split(",");
			String[] ord = orders.split(",");
			for (int i = 0; i < sort.length; i ++) {
				ori_sql += (sort[i] +" "+ ord[i] +",");
			}

			ori_sql = ori_sql.substring(0, ori_sql.lastIndexOf(","));

		}
		List<Map<String, Object>> results = jdbcDao.findForJdbcParam(ori_sql, dataGrid.getPage(), dataGrid.getRows());
		dataGrid.setResults(results);
	}

	public <T> T selectEntityById(String serviceId, Map<String, Object> params, Class<T> clazz) {
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId, params);
		return jdbcDao.findTForJdbc(ori_sql, clazz);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void selectDataGrid(String serviceId, Map<String, Object> params, DataGrid dataGrid, Class clazz, boolean offset) {
		String sortName = "";
		SortDirection order = null;
		if(dataGrid.getSort() != null && !dataGrid.getSort().equals("")){
			sortName = dataGrid.getSort();
		}

		order = dataGrid.getOrder();
		/*
		 * dataGrid.getOrder() 默认返回asc 所以不用判断
		if(dataGrid.getOrder() != null && !dataGrid.getOrder().equals("")){
			order = dataGrid.getOrder();
		}*/
		//从对应路径中，获取SQL [/jeecg/demo/sql/test/JeecgJdbcService_listAllByJdbc.sql]
		//1 根据 serviceId , params 获取mybatyis生成的sql语句
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,params);
		//String countsql = JeecgSqlUtil.getCountSqlBySql(ori_sql);
		SqlServerPageHelper sqlserverPageHelper  = new SqlServerPageHelper(ori_sql, new RowSelection());
		String countsql = sqlserverPageHelper.getCountSql();
		int total = jdbcDao.countByJdbc(countsql);
		dataGrid.setTotal(total);
		if(!sortName.equals("")){
			ori_sql += " ORDER BY ";

			for(String s : sortName.split(",")){
				ori_sql += (s +" "+ order +",");
			}

			ori_sql = ori_sql.substring(0,ori_sql.lastIndexOf(","));

		}
		List results;
		if (offset)
			results = jdbcDao.findTForJdbc(ori_sql,dataGrid.getPage(), dataGrid.getRows(), clazz);
		else
			results = jdbcDao.findTForJdbc(ori_sql, 0, 0, clazz);
		dataGrid.setResults(results);
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public void selectDataGrid(String serviceId, Map<String, Object> params, String orders, DataGrid dataGrid, Class clazz, boolean offset) {
		String sortName = "";
		SortDirection order = null;
		if(dataGrid.getSort() != null && !dataGrid.getSort().equals("")){
			sortName = dataGrid.getSort();
		}

		order = dataGrid.getOrder();
		/*
		 * dataGrid.getOrder() 默认返回asc 所以不用判断
		if(dataGrid.getOrder() != null && !dataGrid.getOrder().equals("")){
			order = dataGrid.getOrder();
		}*/
		//从对应路径中，获取SQL [/jeecg/demo/sql/test/JeecgJdbcService_listAllByJdbc.sql]
		//1 根据 serviceId , params 获取mybatyis生成的sql语句
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,params);
		//String countsql = JeecgSqlUtil.getCountSqlBySql(ori_sql);
		SqlServerPageHelper sqlserverPageHelper  = new SqlServerPageHelper(ori_sql, new RowSelection());
		String countsql = sqlserverPageHelper.getCountSql();
		int total = jdbcDao.countByJdbc(countsql);
		dataGrid.setTotal(total);
		if(!sortName.equals("")){
			ori_sql += " ORDER BY ";
			String[] sort = sortName.split(",");
			String[] ord = orders.split(",");
			for (int i = 0; i < sort.length; i ++) {
				ori_sql += (sort[i] +" "+ ord[i] +",");
			}

			ori_sql = ori_sql.substring(0,ori_sql.lastIndexOf(","));

		}
		List results;
		if (offset)
			results = jdbcDao.findTForJdbc(ori_sql,dataGrid.getPage(), dataGrid.getRows(), clazz);
		else
			results = jdbcDao.findTForJdbc(ori_sql, 0, 0, clazz);
		dataGrid.setResults(results);
	}

	public void selectDataGrid(String serviceId, Map<String, Object> params, List<String> sorts, List<String> orders, DataGrid dataGrid, Class clazz, boolean offset) {
		//1 根据 serviceId , params 获取mybatyis生成的sql语句
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,params);
		SqlServerPageHelper sqlserverPageHelper  = new SqlServerPageHelper(ori_sql, new RowSelection());
		String countsql = sqlserverPageHelper.getCountSql();
		int total = jdbcDao.countByJdbc(countsql);
		dataGrid.setTotal(total);
		if (!ListUtils.isNullOrEmpty(sorts)) {
			ori_sql += " ORDER BY ";
			for (int i = 0; i < sorts.size(); i ++) {
				ori_sql += (sorts.get(i) +" "+ orders.get(i) +",");
			}
			ori_sql = ori_sql.substring(0,ori_sql.lastIndexOf(","));
		}
		List results;
		if (offset){
			if(null == clazz){
				results = jdbcDao.findForJdbc(ori_sql, dataGrid.getPage(), dataGrid.getRows());
			}else{
				results = jdbcDao.findTForJdbc(ori_sql,dataGrid.getPage(), dataGrid.getRows(), clazz);
			}
		} else {
			if(null == clazz){
				results = jdbcDao.findForJdbc(ori_sql);
			}else{
				results = jdbcDao.findTForJdbc(ori_sql, 0, 0, clazz);
			}
		}
		dataGrid.setResults(results);
	}

	public List<Map<String, Object>> selectChart(String serviceId) {
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId);
		return jdbcDao.findForJdbc(ori_sql);
	}

	public List<Map<String,Object>> selectListMap(String serviceId,Map param){
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,param);
//        System.out.println(ori_sql);
        return jdbcDao.findForJdbc(ori_sql);
	}

	public List<Map<String,Object>> selectListMapWithIn(String serviceId,List param){
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,param);
		return jdbcDao.findForJdbc(ori_sql);
	}

	public <T>T save(String serviceId,T t){
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId,t);
		jdbcTemplate.execute(ori_sql);
		return t;
	}

	public void update(String serviceId){
		SqlSession session = sqlSessionFactory.openSession();
		String ori_sql = MybatisHelper.getNamespaceSql(session, serviceId);
		jdbcTemplate.update(ori_sql);
	}
}
